// Kaleidoscope.cpp : Implementation of CKaleidoscope

#include "stdafx.h"
#include "Kaleidoscope.h"

#include "../bot/common.h"

// CKaleidoscope

STDMETHODIMP CKaleidoscope::InterfaceSupportsErrorInfo(REFIID riid)
{
	static const IID* const arr[] = 
	{
		&IID_IKaleidoscope
	};

	for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++)
	{
		if (InlineIsEqualGUID(*arr[i],riid))
			return S_OK;
	}
	return S_FALSE;
}


STDMETHODIMP CKaleidoscope::QueryStatus( 
	/* [unique][in] */ __RPC__in_opt const GUID *pguidCmdGroup,
	/* [in] */ ULONG cCmds,
	/* [out][in][size_is] */ __RPC__inout_ecount_full(cCmds) OLECMD prgCmds[  ],
	/* [unique][out][in] */ __RPC__inout_opt OLECMDTEXT *pCmdText)
{
	if(cCmds == 1)
	{
		prgCmds[1].cmdf = OLECMDF_SUPPORTED | OLECMDF_ENABLED;
	}

	return S_OK;
}

STDMETHODIMP CKaleidoscope::Exec( 
	/* [unique][in] */ __RPC__in_opt const GUID *pguidCmdGroup,
	/* [in] */ DWORD nCmdID,
	/* [in] */ DWORD nCmdexecopt,
	/* [unique][in] */ __RPC__in_opt VARIANT *pvaIn,
	/* [unique][out][in] */ __RPC__inout_opt VARIANT *pvaOut)
{
    LOG_INFO("Begin of CKaleidoscope::Exec");
    HRESULT hr = S_OK;

	IUnknown* pUnknown = NULL;
	hr = this->GetSite(IID_IUnknown, reinterpret_cast<void**>(&pUnknown));
	if(FAILED(hr))
    {
        LOG_FATAL("Failed to get IUnknown, hr=%#X", hr);
        AtlThrow(hr);
    }

    try
    {
        Autobot bot;
        bot.run(pUnknown);
    }
    catch(const std::runtime_error& e)
    {
        LOG_FATAL("Error: %s", e.what());
        MessageBoxA(NULL, e.what(), "Error", MB_OK | MB_ICONERROR);
        hr = S_FALSE;
    }
    catch(const CAtlException& e)
    {
        LOG_FATAL("CAtlException: hr=%#X", e.m_hr);
        MessageBoxA(NULL, "Runtime CAtlException", "Error", MB_OK | MB_ICONERROR);
        hr = S_FALSE;
    }
    catch(...)
    {
        LOG_FATAL("Unknown Error...");
        hr = S_FALSE;
    }

    LOG_INFO("End of CKaleidoscope::Exec");
	return hr;
}
